package com.michael.demo.springcloud.alibaba.seata.order.controller;

import com.michael.demo.springcloud.alibaba.seata.order.entity.Order;
import com.michael.demo.springcloud.alibaba.seata.order.feign.UserAccountService;
import com.michael.demo.springcloud.alibaba.seata.order.service.OrderService;
import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

/**
 * 类功能描述:
 * <pre>
 *   xxxx
 * </pre>
 *
 * @author Michael
 * @version 1.0
 * @date 2021/04/01 17:00
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserAccountService userAccountService;

    @PostMapping(value = "/order")
    public String order(Long userId, String commodityCode, int orderCount) {

        log.info("Order Service Begin ... xid: " + RootContext.getXID());

        int orderMoney = orderCount << 2;

        // 调用用户中心服务扣减用户余额
        String accountResult = deductUserAccount(userId, orderMoney);
        if ("FAILURE".equals(accountResult)) {
            throw new RuntimeException("扣减失败");
        }

        Order order = new Order().setUserId(userId)
                                 .setCommodityCode(commodityCode)
                                 .setCount(orderCount)
                                 .setMoney(orderMoney);
        // 保存订单记录
        boolean result = orderService.order(order);

        //Random random = new Random();
        //if (random.nextBoolean()) {
        //    throw new RuntimeException("OrderController 模拟异常");
        //}

        log.info("Order Service End ... Created " + order);

        return result ? "SUCCESS" : "FAILURE";
    }

    private String deductUserAccount(Long userId, int orderMoney) {
        return userAccountService.deduct(userId, orderMoney);
    }

}
